package com.ynrcc.efiles;

import java.io.File;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.eova.common.utils.db.DbUtil;
import com.eova.config.EovaConfig;
import com.eova.config.EovaConst;
import com.eova.config.EovaInit;
import com.eova.config.PageConst;
import com.eova.engine.DynamicParse;
import com.eova.engine.EovaExp;
import com.eova.model.Button;
import com.eova.model.EovaLog;
import com.eova.model.Menu;
import com.eova.model.MetaField;
import com.eova.model.MetaObject;
import com.eova.model.User;
import com.eova.service.sm;
import com.eova.template.common.config.TemplateConfig;
import com.eova.template.common.util.TemplateUtil;
import com.eova.vo.MenuConfig;
import com.eova.widget.WidgetManager;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.ynrcc.model.Attachment;
import com.ynrcc.model.FileInfo;
import com.jfinal.kit.JsonKit;

public class AttachmentController extends Controller {

	final Controller ctrl = this;

	/** 自定义拦截器 **/
	protected MetaObjectIntercept intercept = null;

	/** 异常信息 **/
	private String errorInfo = "";

	/** 当前操作的主对象 **/
	private final Record record = new Record();

	public void add() throws Exception {
		String objectCode = this.getPara(0);
		MetaObject object = sm.meta.getMeta(objectCode);

		// 字段禁用默认对新增无效
		for (MetaField mf : object.getFields()) {
			mf.put("is_disable", false);
		}

		// 构建关联参数值
		WidgetManager.buildRef(this, object);

		// 业务拦截
		intercept = TemplateUtil.initIntercept(object.getBizIntercept());
		if (intercept != null) {
			AopContext ac = new AopContext(ctrl, object);
			intercept.addInit(ac);
		}

		setAttr("object", object);
		setAttr("fields", object.getFields());
		render("/efiles/attachment/add.html");
	}

	public void doAdd() {

		String objectCode = this.getPara(0);

		final MetaObject object = sm.meta.getMeta(objectCode);

		// 构建对象数据
		final Map<String, Record> reMap = WidgetManager.buildData(this, object.getFields(), record, object.getPk(),
				true);

		intercept = TemplateUtil.initIntercept(object.getBizIntercept());
		// 事务(默认为TRANSACTION_READ_COMMITTED)
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				try {

					AopContext ac = new AopContext(ctrl, record);

					// 新增前置任务
					if (intercept != null) {
						String msg = intercept.addBefore(ac);
						if (!xx.isEmpty(msg)) {
							errorInfo = msg;
							return false;
						}
					}

					if (!xx.isEmpty(object.getTable())) {
						// update table
						Db.use(object.getDs()).save(object.getTable(), object.getPk(), record);
					} else {
						// update view
						WidgetManager.operateView(object.getPk(), reMap, TemplateConfig.ADD);
					}

					// 新增后置任务
					if (intercept != null) {
						String msg = intercept.addAfter(ac);
						if (!xx.isEmpty(msg)) {
							errorInfo = msg;
							return false;
						}
					}
				} catch (Exception e) {
					errorInfo = TemplateUtil.buildException(e);
					return false;
				}
				return true;
			}
		});

		// AOP提示信息
		if (!flag) {
			renderJson(new Easy(errorInfo));
			return;
		}

		if (!flag) {
			renderJson(new Easy("新增失败" + errorInfo));
			return;
		}

		// 记录新增日志
		EovaLog.dao.info(this, EovaLog.ADD, object.getStr("code"));

		// 新增成功之后
		if (intercept != null) {
			try {
				ArrayList<Record> records = new ArrayList<Record>();
				records.add(record);

				AopContext ac = new AopContext(this, records);
				String msg = intercept.addSucceed(ac);
				if (!xx.isEmpty(msg)) {
					errorInfo = msg;
				}
			} catch (Exception e) {
				errorInfo = TemplateUtil.buildException(e);
				renderJson(new Easy("新增成功,addSucceed拦截执行异常!" + errorInfo));
				return;
			}
		}

		renderJson(new Easy());
	}

	public void list() {

		String menuCode = this.getPara(0);

		// 获取元数据
		Menu menu = Menu.dao.findByCode(menuCode);
		MenuConfig config = menu.getConfig();
		String objectCode = config.getObjectCode();
		MetaObject object = MetaObject.dao.getByCode(objectCode);
		List<MetaField> fields = MetaField.dao.queryByObjectCode(objectCode);

		// 根据权限获取功能按钮
		User user = this.getSessionAttr("user");
		List<Button> btnList = Button.dao.queryByMenuCode(menuCode, user.getInt("rid"));

		// 是否需要显示快速查询
		setAttr("isQuery", MetaObject.dao.isExistQuery(objectCode));

		setAttr("menu", menu);
		setAttr("btnList", btnList);
		setAttr("object", object);
		setAttr("fields", fields);

		render("/efiles/attachment/list.html");
	}

	public void detail() throws Exception {
		int id = getParaToInt(0);
		System.out.println(id);
		FileInfo file = FileInfo.dao.findById(id);
		System.out.println(file.get("NAME"));
		setAttr("file_info", file);

		render("/efiles/detail.html");
	}

	public void download() throws Exception {
		int id = getParaToInt(0);
		Attachment attr = Attachment.dao.findById(id);
		EovaInit.initConfig();
		File file = new File(EovaConfig.props.get("filedb") + attr.getPath() + attr.getName());
		System.out.println(file);

		renderFile(file);
	}

	// 用于完整档案中展现附件列表
	public void show() throws Exception {
		int file_id = getParaToInt(0);
		setAttr("file_id", file_id);
		render("/efiles/attachment/show.html");
	}

	// 用于完整档案中展现附件列表
	public void view_gw() throws Exception {
		int id = getParaToInt(0);
		Attachment attr = Attachment.dao.findById(id);
		EovaInit.initConfig();
		String sursenDocFilePath = EovaConfig.props.get("filedb") + attr.getPath();
		String sursenDocFileName = attr.getName();
		System.out
				.println("sursenDocFilePath=[" + sursenDocFilePath + "],sursenDocFileName=[" + sursenDocFileName + "]");
		setAttr("sursenDocFilePath", sursenDocFilePath);
		setAttr("sursenDocFileName", sursenDocFileName);

		render("/efiles/attachment/view_gw.html");
	}

	public void get() throws Exception {
		int file_id = getParaToInt(0);
		String sql = "select * from ATTACHMENT where file_id =" + file_id;
		List<Attachment> attachment = Attachment.dao.find(sql);
		String json = JsonKit.toJson(attachment);
		json = "{\"total\":" + attachment.size() + ",\"rows\":" + json + "}";
		renderJson(json);
	}

	/**
	 * 查找Dialog
	 */
	public void toFind() {
		render("/efiles/attachment/find/find.html");
	}

	/**
	 * 查找框Dialog
	 */
	public void find() {

		String url = "/attachment/findJson?";

		String exp = getPara("exp");
		String code = getPara("code");
		String field = getPara("field");
		boolean isMultiple = getParaToBoolean("multiple", false);
		// 自定义表达式
		if (xx.isEmpty(exp)) {
			// 根据表达式获取ei
			MetaField ei = MetaField.dao.getByObjectCodeAndEn(code, field);
			exp = ei.getStr("exp");
			url += "code=" + code + "&field=" + field;
		} else {
			url += "exp=" + exp;
			try {
				exp = URLDecoder.decode(exp, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		// 动态解析变量和逻辑运算
		exp = DynamicParse.buildSql(exp, this.getSessionAttr(EovaConst.USER));

		// 根据表达式构建元数据
		EovaExp se = new EovaExp(exp);
		MetaObject mo = se.getObject();
		List<MetaField> mfs = se.getFields();
		if (isMultiple) {
			mo.set("is_single", false);
		}
		// mo.set("is_celledit", true);
		// for (MetaField mf : mfs) {
		// mf.set("is_edit", true);
		// mf.put("editor", "eovatext");
		// }

		setAttr("action", url);
		// 用于Grid呈现
		setAttr("objectJson", JsonKit.toJson(mo));
		setAttr("fieldsJson", JsonKit.toJson(mfs));
		// 用于query条件
		setAttr("itemList", mfs);
		// System.out.println(JsonKit.toJson(mo));

		toFind();
	}

	/**
	 * Find Dialog Grid Get JSON
	 */
	public void findJson() {
		/*
		 * String exp = getPara("exp"); String code = getPara("code"); String en
		 * = getPara("field"); System.out.println("exp=[" + exp + "]"); if
		 * (xx.isEmpty(exp)) { // 根据表达式获取ei MetaField ei =
		 * MetaField.dao.getByObjectCodeAndEn(code, en); exp = ei.getStr("exp");
		 * } else { try { exp = URLDecoder.decode(exp, "UTF-8"); } catch
		 * (UnsupportedEncodingException e) { e.printStackTrace(); } }
		 * 
		 * // 动态解析变量和逻辑运算 exp = DynamicParse.buildSql(exp,
		 * this.getSessionAttr(EovaConst.USER)); System.out.println("exp=[" +
		 * exp + "]");
		 */
		String exp = "SELECT id ID,title CN,brchcd BRCHCD,file_year FILE_YEAR FROM FILE_INFO order by id desc";

		// 解析表达式
		EovaExp se = new EovaExp(exp);
		String select = se.simpleSelect;
		String from = se.from;
		String where = se.where;
		String ds = se.ds;
		List<MetaField> eis = se.getFields();

		// 获取分页参数
		int pageNumber = getParaToInt(PageConst.PAGENUM, 1);
		int pageSize = getParaToInt(PageConst.PAGESIZE, 15);

		// 获取条件
		List<Object> parmList = new ArrayList<Object>();
		where = WidgetManager.getWhere(this, eis, parmList, where);
		Object[] parm = new Object[parmList.size()];
		parmList.toArray(parm);

		// 获取排序
		String sort = WidgetManager.getSort(this, se.order);

		// 分页查询Grid数据
		String sql = from + where + sort;
		Page<Record> page = Db.use(ds).paginate(pageNumber, pageSize, select, DbUtil.formatSql(sql), parm);

		// 将分页数据转换成JSON
		String json = JsonKit.toJson(page.getList());
		json = "{\"total\":" + page.getTotalRow() + ",\"rows\":" + json + "}";
		// System.out.println(json);

		renderJson(json);
	}
}
